<?php

namespace app\admin\controller;

use think\Config;
use think\Request;

class Video extends Admin
{
    //TODO 视频管理

    /**
     * 视频列表
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
   public function index()
   {
       //标题搜索
       $name = input('name');
       if(!empty($name)) {
           $where['name'] = ['like',"%$name%"];
       }

       //状态搜索
       if(!empty(input('status'))) {
           $where['status'] = input('status');
       }

       //免费搜索
       if(!empty(input('is_free'))) {
           $where['is_free'] = input('is_free');
       }

       //下载搜索
       if(!empty(input('downloadable'))) {
           $where['downloadable'] = input('downloadable');
       }

       //分类搜索
       $cate_id = input('cate_id');
       if(!empty($cate_id)) {
           $where['cate_id'] = $cate_id;
       }

       //作者搜索
       if(!empty(input('channel_id'))) {
           $where['channel_id'] = input('channel_id');
       }

       //标签搜索
       if(!empty(input('tag'))) {
           $tag = input('tag');
           $where['tag_list'] = ['like',"%$tag%"];
       }

       //分类
       $cate_list = \think\Db::table('video_categories')
           ->where('status',1)
           ->field('id,name')
           ->order('id desc')
           ->select();

       //作者
       $channel_list = \think\Db::table('channels')
           ->field('id,name')
           ->order('id desc')
           ->select();

       $where['id'] = ['>',0];

       $lists = \think\Db::table('videos')
           ->where($where)
           ->order('is_top desc,published_at desc,id desc')
           ->paginate(10,false,[
               'query'     => [
                   'name' => $name,
                   'status' => input('status'),
                   'is_free' => input('is_free'),
                   'downloadable' => input('downloadable'),
                   'cate_id' => input('cate_id'),
                   'channel_id' => input('channel_id'),
                   'tag' => input('tag'),
               ],
           ]);

       $videos = $lists->toArray();
       foreach ($videos['data'] as &$video){
           $video['cate_name'] = '待定';
           $video['channel_name'] = '待定';
           //分类
           $cate = \think\Db::table('video_categories')
               ->where('id',$video['cate_id'])
               ->field('name')
               ->find();
           $video['cate_name'] = $cate['name'];

           //作者
           if(!empty($video['channel_id'])) {
               $cate = \think\Db::table('channels')
                   ->where('id',$video['channel_id'])
                   ->field('name')
                   ->find();
               $video['channel_name'] = $cate['name'];
           }
           //标签
           $tags = explode(',',$video['tag_list']);
           $video['tag_lists'] = $tags;

           //$video['favorite_count'] = \think\Db::table('user_favorite_videos')->where('video_id',$video['id'])->count();

       }
       unset($course);

       $page = $lists->render();
       $total = $lists->total();

       return view('index',[
           'lists' => $videos['data'],
           'cates' => $cate_list,
           'channels' => $channel_list,
           'page' => $page,
           'total' => $total
       ]);
   }

    /**
     * 添加视频
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
   public function add()
   {
       //分类
       $cate = \think\Db::table('video_categories')
           ->where('status',1)
           ->order('id desc')
           ->select();

       //作者
       $channel = \think\Db::table('channels')
           ->order('id desc')
           ->select();

       //标签
       $tag = \think\Db::table('tags')
           ->where('status',1)
           ->order('order desc,id desc')
           ->field('name')
           ->select();

       return view('video_add',['cates' => $cate,'channels' => $channel,'tags' => $tag]);
   }

    /**
     * 视频添加提交
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
   public function addPost()
   {
       $validate = new \think\Validate([
           'name| 标题' => 'require',
           'desc| 描述' => 'require',
           'video_url| 播放地址' => 'require',
           'tag| 标签' => 'require',
           'cate_id| 所属分类' => 'require',
           'channel_id| 所属作者' => 'require',
       ]);
       $request_data = input();

       if (!$validate->check($request_data)) {
           $this->error($validate->getError());
       }

       $time = strtotime($request_data['date'].' '.$request_data['time']);
       $data = [
           'cate_id' => $request_data['cate_id'],
           'channel_id' =>$request_data['channel_id'],
           'name' =>$request_data['name'],
           'desc' =>$request_data['desc'],
           'price' =>$request_data['price'],
           'shares_count' =>$request_data['shares_count'],
           'played_count' =>$request_data['played_count'],
           'favorites_count' =>$request_data['favorites_count'],
           'download_count' =>$request_data['download_count'],
           'share_name' =>$request_data['share_name'],
           'share_url' =>$request_data['share_url'],
           'downloadable' =>$request_data['downloadable'],
           'is_free' =>$request_data['is_free'],
           'is_top' =>$request_data['is_top'],
           'status' =>$request_data['status'],
           'poster' => $request_data['poster_url'],
           'url' => $request_data['video_url'],
           'demo_url' => $request_data['demo_video_url'],
           'published_at' => date('Y-m-d H:i:s',$time),
           'tag_list' => implode(',',$request_data['tag']),
       ];

       $video_id = \think\Db::table('videos')->insertGetId($data);
       writeAdminLog(session('VideoAdmin.name'),' 添加视频 ' . $request_data['title']); //后台管理日志
       $this->push_message($video_id); //新增视频触发极光推送
       $this->success('添加成功！','/admin/video/index');
   }

    /**
     * 编辑视频
     * @param $id
     * @return \think\response\View
     */
   public function edit($id)
   {
       $info = \think\Db::table('videos')->where('id',$id)->find();
       $info['date'] = date('Y-m-d',strtotime($info['published_at']));
       $info['time'] = date('H:i:s',strtotime($info['published_at']));

       //分类
       $cate = \think\Db::table('video_categories')
           ->where('status',1)
           ->order('id desc')
           ->select();

       //作者
       $channel = \think\Db::table('channels')
           ->order('id desc')
           ->select();

       //标签
       $tag = \think\Db::table('tags')
           ->where('status',1)
           ->order('order desc,id desc')
           ->select();

       return view('video_edit',['info' => $info,'cates' => $cate,'channels' => $channel,'tags' => $tag]);
   }

    /**
     * 提交编辑数据
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
   public function editPost()
   {
       $validate = new \think\Validate([
           'name| 标题' => 'require',
           'desc| 描述' => 'require',
           'video_url| 播放地址' => 'require',
           'tag| 标签' => 'require',
           'cate_id| 所属分类' => 'require',
           'channel_id| 所属作者' => 'require',
       ]);
       $request_data = input();

       if (!$validate->check($request_data)) {
           $this->error($validate->getError());
       }

       $time = strtotime($request_data['date'].' '.$request_data['time']);
       $data = [
           'cate_id' => $request_data['cate_id'],
           'channel_id' =>$request_data['channel_id'],
           'name' =>$request_data['name'],
           'desc' =>$request_data['desc'],
           'price' =>$request_data['price'],
           'shares_count' =>$request_data['shares_count'],
           'played_count' =>$request_data['played_count'],
           'favorites_count' =>$request_data['favorites_count'],
           'download_count' =>$request_data['download_count'],
           'share_name' =>$request_data['share_name'],
           'share_url' =>$request_data['share_url'],
           'downloadable' =>$request_data['downloadable'],
           'is_free' =>$request_data['is_free'],
           'is_top' =>$request_data['is_top'],
           'status' =>$request_data['status'],
           'poster' => $request_data['poster_url'],
           'url' => $request_data['video_url'],
           'demo_url' => $request_data['demo_video_url'],
           'published_at' => date('Y-m-d H:i:s',$time),
           'tag_list' => implode(',',$request_data['tag']),
       ];

       \think\Db::table('videos')->where('id',$request_data['id'])->update($data);

       writeAdminLog(session('VideoAdmin.name'),' 编辑视频 ' . $request_data['title']); //后台管理日志
       $this->success('编辑成功！','/admin/video/index');
   }


   //TODO 分类管理

    /**
     * 分类页
     */
    public function cate()
    {
        $lists = \think\Db::table('video_categories')
            ->order("id desc")
            ->paginate(20);

        return view('cate',['lists' => $lists]);
    }

    /**
     * 添加分类
     * @return \think\response\Json
     */
    public function addCate()
    {
        $validate = new \think\Validate([
            'name| 分类名' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }

        $info = \think\Db::table('video_categories')
            ->where('name', $request_data['name'])
            ->find();
        if(!empty($info)) {
            return error('数据已存在');
        }

        $data = [
            'name' => $request_data['name'],
            'status' => $request_data['status'],
        ];

        \think\Db::table('video_categories')->insert($data);
        writeAdminLog(session('VideoAdmin.name'),' 添加视频分类 ' . $request_data['name']); //后台管理日志
        return success('成功添加分类！');
    }

    /**
     * 获取编辑的分类
     * @return \think\response\Json
     */
    public function editCate()
    {
        $validate = new \think\Validate([
            'id| ID' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }

        $info = \think\Db::table('video_categories')
            ->where('id',$request_data['id'])
            ->find();

        return success('编辑分类！',$info);
    }

    /**
     * 编辑数据提交
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editCatePost()
    {
        $validate = new \think\Validate([
            'id| ID' => 'require',
            'name| 分类名' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }

        $info = \think\Db::table('video_categories')
            ->where('name', $request_data['name'])
            ->find();
        if(!empty($info)) {
            return error('数据已存在');
        }

        $data = [
            'name' => $request_data['name'],
            'status' => $request_data['status'],
        ];

        \think\Db::table('video_categories')
            ->where('id',$request_data['id'])
            ->update($data);

        writeAdminLog(session('VideoAdmin.name'),' 编辑视频分类 ' . $request_data['name']); //后台管理日志
        return success('成功编辑分类！');
    }


   //TODO 标签管理
    /**
     * 标签列表
     */
    public function tag()
    {
        $lists = \think\Db::table('tags')
            ->order("order desc,id desc")
            ->paginate(20);

        return view('tag',['lists' => $lists]);
    }

    /**
     * 添加标签
     * @return \think\response\Json
     */
    public function addTag()
    {
        $validate = new \think\Validate([
            'name| 标签名' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }

        $info = \think\Db::table('tags')
            ->where('name', $request_data['name'])
            ->find();
        if(!empty($info)) {
            return error('该标签已存在');
        }

        $data = [
            'order' => $request_data['order'],
            'name' => $request_data['name'],
            'status' => $request_data['status'],
        ];

        \think\Db::table('tags')->insert($data);
        writeAdminLog(session('VideoAdmin.name'),' 添加标签 ' . $request_data['name']); //后台管理日志
        return success('成功添加！');
    }

    /**
     * 获取编辑的分类
     * @return \think\response\Json
     */
    public function editTag()
    {
        $validate = new \think\Validate([
            'id| ID' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }

        $info = \think\Db::table('tags')
            ->where('id',$request_data['id'])
            ->find();

        return success('编辑标签！',$info);
    }

    /**
     * 编辑数据提交
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editTagPost()
    {
        $validate = new \think\Validate([
            'id| ID' => 'require',
            'name| 分类名' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }

        $info = \think\Db::table('tags')
            ->where('name', $request_data['name'])
            ->find();
        if(!empty($info)) {
            return error('该标签已存在');
        }

        $data = [
            'name' => $request_data['name'],
            'order' => $request_data['order'],
            'status' => $request_data['status'],
        ];

        \think\Db::table('tags')
            ->where('id',$request_data['id'])
            ->update($data);

        writeAdminLog(session('VideoAdmin.name'),' 编辑标签 ' . $request_data['name']); //后台管理日志
        return success('成功编辑标签！');
    }

    /**
     * 上传图片
     */
    public function uploadFile()
    {
        $file = request()->file('file');
        if (empty($file)) {
            return  error("图片错误！");
        } else {
            $info = $file->getInfo();

            if ($info) {

                $object = 'image/' . $info['name'];

                $pictureName = getOssUrl($info['tmp_name'],$object,'image',2);

            } else {
                echo $file->getError();
            }
        }
        return success('上传成功',['url' => "https://".Config::get('OSS.OSS_URL').'/'.$pictureName]);
    }

    /**
     * 上传视频
     */
    public function uploadVideo()
    {
        ini_set("memory_limit","-1");
        $file = request()->file('file');
        if (empty($file)) {
            return error("视频错误,请确保 mp4的视频格式！");
        } else {
            $info = $file->getInfo();

            if ($info) {

                $object = 'video/' . $info['name'];

                $pictureName = getOssVideoUrl($info['tmp_name'],$object,'video');

            } else {
                echo $file->getError();
            }
        }
        return success('上传成功',['url' => "https://".Config::get('OSS.OSS_URL').'/'.$pictureName]);
    }



    /**
     * 更改状态
     */
    public function changeStatus()
    {
        $field = input('field');
        $id = input('id');
        $type = input('type');

        switch ($type){
            case 'cate': //视频分类
                $info = \think\Db::table('video_categories')
                    ->where('id',$id)
                    ->field("$field,name")
                    ->find();

                $status = $info[$field] == 1? 2 : 1;

                \think\Db::table('video_categories')
                    ->where('id',$id)
                    ->update(["$field" => "$status"]);

                writeAdminLog(session('VideoAdmin.name'),' 编辑视频分类 ' . $info['name'] . ' 状态'); //后台管理日志
                break;
            case 'tag'://视频专栏
                $info = \think\Db::table('tags')
                    ->where('id',$id)
                    ->field("$field,name")
                    ->find();

                $status = $info[$field] == 1? 2 : 1;

                \think\Db::table('tags')
                    ->where('id',$id)
                    ->update(["$field" => "$status"]);

                writeAdminLog(session('VideoAdmin.name'),' 编辑标签 ' . $info['name'] . ' 状态'); //后台管理日志
                break;
            case 'video'://视频专栏
                $info = \think\Db::table('videos')
                    ->where('id',$id)
                    ->field("$field,name")
                    ->find();

                $status = $info[$field] == 1? 2 : 1;

                \think\Db::table('videos')
                    ->where('id',$id)
                    ->update(["$field" => "$status"]);

                writeAdminLog(session('VideoAdmin.name'),' 编辑视频 ' . $info['name'] . ' 状态'); //后台管理日志
                return success('更改状态');
                break;
        }
    }


    /**
     * 删除视频
     */
    public function deleted()
    {
        $type = input('type');
        $id = input('id');
        $ids = input('ids');

        switch ($type) {
            //视频分类
            case 'cate':
                if(empty($ids)) {
                    \think\Db::table('video_categories')
                        ->where('id',$id)
                        ->delete();
                }else{
                    $ids = explode(',',$ids);
                    foreach ($ids as $id) {
                        \think\Db::table('video_categories')
                            ->where('id',$id)
                            ->delete();
                    }
                }
                writeAdminLog(session('VideoAdmin.name'),' 删除视频分类ID：' . $id); //后台管理日志
                break;
            //课程管理
            case 'tag':
                if(empty($ids)) {
                    \think\Db::table('tags')
                        ->where('id',$id)
                        ->delete();
                }else{
                    $ids = explode(',',$ids);
                    foreach ($ids as $id) {
                        \think\Db::table('tags')
                            ->where('id',$id)
                            ->delete();
                    }
                }
                writeAdminLog(session('VideoAdmin.name'),' 删除标签ID：' . $id); //后台管理日志
                break;
            //视频管理
            case 'video':
                if(empty($ids)) {
                    \think\Db::table('videos')
                        ->where('id',$id)
                        ->delete();
                }else{
                    $ids = explode(',',$ids);
                    foreach ($ids as $id) {
                        \think\Db::table('videos')
                            ->where('id',$id)
                            ->delete();
                    }
                }
                writeAdminLog(session('VideoAdmin.name'),' 删除视频ID：' . $id); //后台管理日志
                break;
        }
        return success('删除成功');
    }

    /**
     * 视频评论
     * @param Request $request
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function comment(Request $request)
    {
        $video_name = $request->param('name');
        if(!empty($video_name)) {
            $video_info = \think\Db::table('videos')->whereLike('name',"%$video_name%")->field('id')->find();
            $where['video_id'] = $video_info['id'];
        }
        $where['is_show'] = 1;
        $lists = \think\Db::table('user_comments')
            ->where($where)
            ->order('updated_at desc')
            ->paginate(6)->each(function ($item,$key){
                $video = \think\Db::table('videos')
                    ->where('id',$item['video_id'])
                    ->field('name')
                    ->find();

                $user = \think\Db::table('users')
                    ->where('id',$item['user_id'])
                    ->field('name,avatar')
                    ->find();
                $item['video_name'] = $video['name'];
                $item['user_name'] = $user['name'];
                $item['user_avatar'] = $user['avatar'];
                $item['replies_count'] = \think\Db::table('user_replies')
                    ->where('comment_id',$item['id'])
                    ->where('is_show',1)
                    ->where('reply_user_id',0)
                    ->count();

                $item['lists'] = \think\Db::table('user_replies')
                    ->where('comment_id',$item['id'])
                    ->where('is_show',1)
                    ->where('reply_user_id',0)
                    ->select();

                foreach ($item['lists'] as &$list){
                    $info = \think\Db::table('users')
                        ->where('id',$list['user_id'])
                        ->field('name,avatar')
                        ->find();
                    $list['user_name'] = $info['name'];
                    $list['user_avatar'] = $info['avatar'];
                    $list['replies_count'] = \think\Db::table('user_replies')
                        ->where('is_show',1)
                        ->where('reply_user_id',$list['user_id'])
                        ->where('comment_id',$list['comment_id'])
                        ->count();
                    $list['replies_lists'] = \think\Db::table('user_replies')
                        ->where('reply_user_id',$list['user_id'])
                        ->where('comment_id',$list['comment_id'])
                        ->where('is_show',1)
                        ->select();

                    foreach ($list['replies_lists'] as &$replies_list) {
                        $user_info = \think\Db::table('users')
                            ->where('id',$replies_list['user_id'])
                            ->field('name,avatar')
                            ->find();
                        $replies_list['user_name'] = $user_info['name'];
                        $replies_list['user_avatar'] = $user_info['avatar'];
                    }

                }

                return $item;
        });
        //var_dump($lists);die;
        return view('comment',compact('lists'));
    }

    /**
     * 删除评论
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function comment_delete(Request $request)
    {
        $id = $request->param('id');
        $result = \think\Db::table('user_comments')->where('id',$id)->update(['is_show' => 2]);
        if($result) {
            return success('删除成功');
        }
        return error('删除失败');
    }

    /**
     * 删除评论回复
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function replies_delete(Request $request)
    {
        $id = $request->param('id');
        $result = \think\Db::table('user_replies')->where('id',$id)->update(['is_show' => 2]);
        if($result) {
            return success('删除成功');
        }
        return error('删除失败');
    }

    /**
     * 添加评论点赞数
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function comment_zan(Request $request)
    {
        $validate = new \think\Validate([
            'id| ID' => 'require',
            'zan| 点赞数' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }
        $id = $request->param('id');
        $zan = $request->param('zan');
        $info = \think\Db::table('user_comments')->where('id',$id)->field('zan')->find();
        $result = \think\Db::table('user_comments')->where('id',$id)->update(['zan' => $info['zan'] + $zan]);
        if($result) {
            return success('操作成功');
        }
        return error('操作失败');
    }

    /**
     * 添加回复点赞数
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function replies_zan(Request $request)
    {
        $validate = new \think\Validate([
            'id| ID' => 'require',
            'zan| 点赞数' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }
        $id = $request->param('id');
        $zan = $request->param('zan');
        $info = \think\Db::table('user_replies')->where('id',$id)->field('zan')->find();
        $result = \think\Db::table('user_replies')->where('id',$id)->update(['zan' => $info['zan'] + $zan]);
        if($result) {
            return success('操作成功');
        }
        return error('操作失败');
    }

    /**
     * 推送新视频消息
     * @param $video_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function push_message($video_id)
    {
        //实例化极光推送类
        $push_config = ['push_app_key','push_master_secret'];
        foreach ($push_config as $config) {
            $item = \think\Db::table('system')->where(['key' => $config])->field('value')->find();
            $configs[$config] = $item['value'];
        }

        $pushmodel = new \JPush\Client($configs['push_app_key'],$configs['push_master_secret']);

        $video = \think\Db::table('videos')->where('id',$video_id)->field('name,channel_id')->find();
        $channel = \think\Db::table('channels')->where('id',$video['channel_id'])->field('name')->find();

        $users[] = '191e35f7e01136ae714';
        //别名推送方法
        $user_lists = \think\Db::table('user_focus_channels')->where('channel_id',$video['channel_id'])->select();

        foreach ($user_lists as $list) {
            $user = \think\Db::table('users')->where('id',$list['user_id'])->find('device_token');
            if(!empty($user['device_token'])) {
                $users[] = $user['device_token'];
            }
        }

        $data = $pushmodel->push()
            ->setPlatform('ios')
            ->addRegistrationId($users)
            ->message('视频更新：' . $video['name'] . ' >>', [
                'title' => '特别关注 ' . $channel['name'],
                'content_type' => 'text',
            ])
            ->send();

        return $data;
    }

}
